<?php

namespace app\shop\controller;

use app\common\model\admin\AccountModel;
use app\common\model\admin\AccountStoreModel;
use app\common\model\collect\OrderExpressGoodsModel;
use app\common\model\collect\OrderExpressModel;
use app\common\model\jiyun\warehouse\WarehouseModel;
use app\common\model\shop\PlatformModel;
use think\admin\Controller;
use think\admin\helper\QueryHelper;

/**
 * 采购订单
 * @class Order
 * @package app\jiyun\controller\order
 * @auth shirukun
 * @date 2024/11/21 16:32
 */
class OrderExpress extends Controller
{
    // 不过滤account_id
    public $check_account = false;

    // 不过滤user_id
    public $check_user = false;

    /**
     * 待确认列表
     * @auth true
     * @menu true
     */
    public function index()
    {
        OrderExpressModel::mQuery()->layTable(function (){
            $this->title = lang('采购订单列表');

            // 公司列表
            if ($this->super) {
                $this->account_list = AccountModel::mk()->where(['status'=> 1])->column('title', 'id');
            }else{
                $this->account_list = [];
            }
            // 状态
            $this->status = OrderExpressModel::getStatus();
            // 平台列表
            $this->platform_list = PlatformModel::mk()->where(['status' => 1])->column('title', 'id');

        },function (QueryHelper $query){

            // 数据权限过滤
            if (!$this->super) {
                $query->where('shop_account_id', $this->adminUser['account_id']);
            }

            $query->order('id desc')->where(['status'=>-1,'is_merge'=>0]);
            $query->like("order_no,express_no")->equal("shop_account_id#account_id,status");

        });
    }

    protected function _index_page_filter(&$data){
        if ($this->super) {
            // 公司列表
            $account_list = AccountModel::mk()->where(['status' => 1])->column('title', 'id');
        }else{
            // 公司列表
            $account_list = [];
        }
        // 状态
        $status = OrderExpressModel::getStatus();

        foreach ($data as &$item) {
            $item['company_name'] = $account_list[$item['shop_account_id']] ?? "-";
            $item['status_title'] = $status[$item['status']] ?? "-";
        }
    }

    /**
     * 已确认列表
     * @auth true
     * @menu true
     */
    public function index_confirm()
    {
        OrderExpressModel::mQuery()->layTable(function (){
            $this->title = lang('采购订单列表');

            // 公司列表
            if ($this->super) {
                $this->account_list = AccountModel::mk()->where(['status'=> 1])->column('title', 'id');
            }else{
                $this->account_list = [];
            }
            // 状态
            $this->status = OrderExpressModel::getStatus();
            // 平台列表
            $this->platform_list = PlatformModel::mk()->where(['status' => 1])->column('title', 'id');

        },function (QueryHelper $query){

            // 数据权限过滤
            if (!$this->super) {
                $query->where('shop_account_id', $this->adminUser['account_id']);
            }

            $query->order('id desc')->where([['status','<>',-1],['is_merge','=',0]]);
            $query->like("order_no,express_no")->equal("shop_account_id#account_id,status");

        });
    }

    protected function _index_confirm_page_filter(&$data){
        if ($this->super) {
            // 公司列表
            $account_list = AccountModel::mk()->where(['status' => 1])->column('title', 'id');
        }else{
            // 公司列表
            $account_list = [];
        }
        // 仓库列表
        $warehouse_list = WarehouseModel::mk()->column('warehouse_c_name', 'id');
        // 状态
        $status = OrderExpressModel::getStatus();

        foreach ($data as &$item) {
            $item['company_name'] = $account_list[$item['shop_account_id']] ?? "-";
            $item['warehouse_c_name'] = $warehouse_list[$item['warehouse_id']] ?? "-";
            $item['status_title'] = $status[$item['status']] ?? "-";
        }
    }

    /**
     * 添加
     * @auth true
     */
    public function add()
    {
        
    }

    /**
     * 编辑
     * @auth true
     */
    public function edit()
    {
        
    }

    /**
     * 详情
     * @auth true
     */
    public function info()
    {

        $id = input('id');
        $order_express_goods = OrderExpressGoodsModel::mk()->where(['order_express_id'=>$id])->select()->toArray();
//        halt(json_encode($order_express_goods));
        $this->order_express_goods = json_encode($order_express_goods,320);

        OrderExpressModel::mForm("info");
    }

    /**
     * 表单前置回调
     */
    protected function _form_filter(array &$data)
    {
        if ($this->request->isPost()) {
//            $rule = [
//                "shop_account_id|".lang('公司')    =>  "require|integer",
////                "order_no|".lang('系统单号')    =>  "require|length:1,100",
//                "other_order_no|".lang('第三方订单号')    =>  "require|length:1,100",
//                "express_name|".lang('物流名称')    =>  "require|length:1,20",
//                "express_no|".lang('物流单号')    =>  "require|length:1,20",
//                "good_name|".lang('商品名称')    =>  "require|length:1,255",
//                "spu_code|".lang('商品spu')    =>  "require|length:1,100",
//                "sku_code|".lang('商品规格sku')    =>  "require|length:1,100",
//                "num|".lang('商品数量')    =>  "require|number",
//                "price|".lang('商品价格')    =>  "float",
//                "spec_data|".lang('规格')    =>  "require|length:1,200",
//                "spec_value|".lang('规格值')    =>  "require|length:1,200",
//                "item_url|".lang('商品地址')    =>  "length:1,255",
//                "order_detail_url|".lang('订单详情地址')    =>  "length:1,255",
//            ];
//            $validate = new \think\Validate;
//
//            // 使用 rule 方法指定验证规则
//            $validate->rule($rule);
//            if (!$validate->check($data)) {
//                $this->error($validate->getError());
//            }
//
//            // 生成系统订单号
//            $other_order_no_count = OrderInfoExpressModel::where(['other_order_no'=>$data['other_order_no']])->count();
//            $data['order_no'] = $data['other_order_no'] . '-' . ($other_order_no_count+1);

        }else{
            // 公司列表
            if ($this->super) {
                $this->account_list = AccountModel::mk()->where(['status'=> 1])->column('title', 'id');
            }else{
                $this->account_list = [];
            }
            // 仓库列表
            $this->warehouse_list = WarehouseModel::mk()->column('warehouse_c_name', 'id');
        }
    }

    /**
     * 删除
     * @auth true
     */
    public function remove()
    {
        $id = input('id');
        OrderExpressGoodsModel::mk()->where([['order_express_id','in',$id]])->delete();
        OrderExpressModel::mDelete();
    }

    /**
     * 同步到集运
     * @auth true
     */
    public function syncOrderTojy ()
    {

        if ( $this->request->isPost() ) {

            $order_ids = $this->request->param('order_ids');
            $warehouse_id = $this->request->param('warehouse_id');

            // 获取仓库信息
            $warehouse = WarehouseModel::mk()->find($warehouse_id);
//            halt($warehouse['account_id']);

            try {

                // 更新表数据
                OrderExpressModel::where([['id','in',$order_ids]])->update([
                    'account_id' => $warehouse['account_id'], // 集运公司id
                    'warehouse_id' => $warehouse_id, // 仓库id
                    'status' => 0, // 待签收
                    'confirm_time' => date('Y-m-d H:i:s'), // 推送时间
                ]);

            }catch (\Exception $e){
                $this->error($e->getMessage());
            }

            $this->success('提交成功');

        } else {

            $order_ids = $this->request->param('id');
            $shop_account_ids   = $this->request->get('shop_account_id');

            $shop_account_arr = array_unique(explode(',', $shop_account_ids));
            // 判断是否是同一家的订单
            if (count($shop_account_arr) > 1) {
                $this->error('只能推送 同一个公司的订单');
            }

            // 获得配置商家的仓库
            $warehouse_id_arr = AccountStoreModel::mk()->where('account_id', $shop_account_ids)->column('warehouse_id');
            $warehouse_arr = WarehouseModel::mk()->whereIn('id', $warehouse_id_arr)->select()->column('warehouse_c_name', 'id');

            $this->warehouse_arr = $warehouse_arr;
            $this->order_ids     = $order_ids;

            $this->fetch('sync');
        }

    }
}
